/**
 * 
 */
package com.sc.softmgr.common.filter;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.acc.softmgr.model.SysUser;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.sc.softmgr.business.service.GrayService;

/**
 * 
 * @content
 * 
 * @date 2017年6月19日
 * 
 * @author OprCalf
 * 
 */
@Component
public class GrayRequestFilter extends ZuulFilter {

	private static final Logger log = LoggerFactory.getLogger(GrayRequestFilter.class);

	@Autowired
	private GrayService grayService;

	@Override
	public String filterType() {
		return "route";
	}

	@Override
	public int filterOrder() {
		return 1;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		log.info("灰度前的服务:" + ctx.get("serviceId"));
		Object obj = request.getSession().getAttribute("currentUser");
		if (obj != null && (obj instanceof SysUser)) {
			SysUser sysUser = (SysUser) obj;
			JSONObject json = grayService.getGrayService(sysUser.getUsername(), ctx.get("serviceId").toString());
			if (json != null && json.get("grayServiceName") != null
					&& StringUtils.isNotBlank(json.get("grayServiceName").toString())) {
				ctx.set("serviceId", json.get("grayServiceName").toString());
			}
		}
		log.info("灰度后的服务:" + ctx.get("serviceId"));
		return null;
	}
}
